package com.cong.security.app.authentication;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.www.BasicAuthenticationConverter;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * 成功处理函数
 */
@Slf4j
@Component("myAuthenticationSuccessHandler")
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    /**
     * 工具类，将authentication转换成为json
     */
    @Autowired
    private ObjectMapper objectMapper;

    // 读取信息
    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private AuthorizationServerTokenServices authorizationServerTokenServices;

    private BasicAuthenticationConverter authenticationConverter = new BasicAuthenticationConverter();

    /**
     * Authentication封装认证信息
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        // 验证clientId及secret，SpringSecurity升级之后将方法抽取出来了，所以就不需要拷贝代码了
        UsernamePasswordAuthenticationToken authRequest = this.authenticationConverter.convert(request);
        if (authRequest == null) {
            log.info("从请求头中未获取到client信息");
            throw new UnapprovedClientAuthenticationException("请求头参数不合法,不予处理");
        }
        String clientId = authRequest.getName();
        // 从请求中获取ClientId,利用ClientDetailsService接口获取到ClientDetails对象
        ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
        // 简单的校验
        if (client == null) {
            log.info("clientId:[{}]不存在", clientId);
            throw new UnapprovedClientAuthenticationException("clientId     " + clientId + "    不存在");
        } else if (!StringUtils.equals(authRequest.getCredentials().toString(), client.getClientSecret())) {
            // 判断密码是否匹配
            log.info("用户输入的clientId:[{}]对应的clientSecret:[{}]与系统存储的secret:[{}]不匹配", clientId, client.getClientSecret(), authRequest.getCredentials().toString());
            throw new UnapprovedClientAuthenticationException("clientSecret不匹配");
        }
        // ClientDetails信息无误，开始new TokenRequest
        // authentication已经有信息，不需要重复获取
        TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP, clientId, client.getScope(), "custom");
        // 创建OAuth2Request
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(client);
        // 拼OAuth2Authentication
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        // 生成access_token
        OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        // 配置返回json
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(oAuth2AccessToken));
    }
}
